<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="备件信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item prop="category" label="种类">
                  <px-select v-model="formValue.category" @change="handleCategoryChange" filterable clearable placeholder="请选择种类">
                    <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="名称" prop="sparePartName">
                  <px-input v-model="formValue.sparePartName" placeholder="请输入备品备件/耗材名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="编码" prop="sparePartCode">
                  <px-input v-model="formValue.sparePartCode" placeholder="请输入备品备件/耗材编码" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="类型" prop="typeCode">
                  <px-tree-select
                    :disabled="!formValue.className"
                    v-model="formValue.typeCode"
                    placeholder="请先选择种类和科室"
                    filterable
                    clearable
                    :data="typeList"
                    :render-after-expand="false"
                    :props="{ children: 'children', label: 'name', value: 'code' }"
                    @visible-change="initTypeList"
                    @change="handleTypeChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="品牌" prop="brandCode">
                  <px-select
                    :disabled="!formValue.typeCode"
                    v-model="formValue.brandCode"
                    filterable
                    clearable
                    placeholder="请先选择类型"
                    @focus="initBrandList"
                    @change="handleBrandChange"
                  >
                    <px-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="厂商型号" prop="supplyModel">
                  <px-select
                    :disabled="!formValue.brandCode"
                    v-model="formValue.supplyModel"
                    placeholder="请先选择品牌"
                    filterable
                    clearable
                    @focus="initSupplyModelList"
                    @change="changeSupplyModel"
                  >
                    <px-option v-for="item in supplyModelList" :key="item.id" :label="item.supplyModel" :value="item.supplyModel" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="厂内型号" prop="model">
                  <px-input v-model="formValue.model" placeholder="根据厂商型号获取" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipSystemTree
                  :className="formValue.className"
                  :systemCode="formValue.systemVal"
                  propValue="systemVal"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                />
              </px-col>
              <px-col :span="8">
                <px-form-item label="单位" prop="sparePartUnit">
                  <px-select v-model="formValue.sparePartUnit" placeholder="请选择单位" filterable clearable>
                    <px-option v-for="item in sparePartUnitList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="库位" prop="warehousePosition">
                  <px-select v-model="formValue.warehousePosition" placeholder="请选择存放库位" filterable clearable>
                    <px-option v-for="item in warehousePositionList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="等级" prop="sparePartLevel">
                  <px-select v-model="formValue.sparePartLevel" placeholder="请选择备品备件/耗材等级" filterable clearable>
                    <px-option v-for="item in sparePartLevelList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="图件号" prop="mapNum">
                  <px-input v-model="formValue.mapNum" placeholder="请输入图件号" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="责任人" prop="principalId">
                  <px-select-v2
                    v-model="formValue.principalId"
                    filterable
                    clearable
                    :options="principalIdList"
                    placeholder="请选择责任人"
                    @change="principalChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="责任人电话" prop="principalPhone">
                  <px-input v-model="formValue.principalPhone" placeholder="选择责任人后带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="额定使用寿命">
                  <px-input-number
                    style="width: calc(70% - 16px); margin-right: 16px"
                    v-model="formValue.usedLife"
                    placeholder="请输入额定使用寿命"
                    :min="1"
                    maxlength="50"
                  />
                  <px-select style="width: 30%" v-model="formValue.usedLifeUnit" placeholder="请选择单位" filterable clearable>
                    <px-option v-for="item in usedLifeUnitList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="16">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入备注"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="库存设置">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="安全库存量" prop="alarmStock">
                  <px-input-number v-model.number="formValue.alarmStock" placeholder="请输入安全库存量" :min="0" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="应备数量" prop="shouldStock">
                  <px-input-number v-model.number="formValue.shouldStock" placeholder="如不填写，默认值为0" :min="0" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="库存上限" prop="maxStock">
                  <px-input-number v-model.number="formValue.maxStock" placeholder="如不填写，默认值为99999" :min="0" maxlength="50" />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="备件图片">
          <template v-slot:content>
            <PhotoUpload
              v-if="!isMain && !isView"
              :photoType="photoType"
              :photoData="{ moduleName: moduleName }"
              :photoList="formValue.pictureLists"
              style="margin-bottom: 18px"
              @changePhotoList="changePhotoList"
              @savePhotoStatus="savePhotoStatus"
            />
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="关联文档">
          <template v-slot:content>
            <FileUpload
              v-if="!isMain && !isView"
              :fileType="fileType"
              :fileData="{ moduleName: moduleName }"
              :fileList="formValue.fileLists"
              style="margin-bottom: 18px"
              @changeFileList="changeFileList"
              @saveFileStatus="saveFileStatus"
            />
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import {
  queryListTree_1,
  queryListPage_5,
  queryBrandList,
  addSparePartsLedgerNew,
  editSparePartsLedgerNew,
  getModuleNameNew,
  getSparePartsLedgerNew
} from "@/api/equip/spareParts";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    category: "",
    sparePartName: "",
    sparePartCode: "",
    className: "",
    systemVal: "",
    typeCode: "",
    brandCode: "",
    modelCode: "",
    supplyModel: "",
    model: "",
    sparePartUnit: "",
    warehousePosition: "",
    sparePartLevel: "",
    mapNum: "",
    principalId: null,
    principalName: "",
    principalPhone: "",
    usedLife: "",
    usedLifeUnit: "hour",
    remark: "",
    alarmStock: "",
    shouldStock: "",
    maxStock: "",
    pictureLists: [],
    fileLists: []
  },
  categoryList: [], // 种类下拉框
  typeList: [], // 类型下拉框
  brandList: [], // 品牌下拉框
  supplyModelList: [], // 厂商型号下拉框
  sparePartUnitList: [], // 单位下拉框
  warehousePositionList: [], // 库位下拉框
  sparePartLevelList: [], // 等级下拉框
  principalIdList: [], // 责任人下拉框
  usedLifeUnitList: [],
  photoType: "add",
  fileType: "add",
  moduleName: "",
  photoStatusFlag: false,
  fileStatusFlag: false
});
const {
  formValue,
  categoryList,
  typeList,
  brandList,
  supplyModelList,
  sparePartUnitList,
  warehousePositionList,
  sparePartLevelList,
  principalIdList,
  usedLifeUnitList,
  photoType,
  fileType,
  moduleName,
  photoStatusFlag,
  fileStatusFlag
} = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  category: [{ required: true, message: "种类不能为空", trigger: "blur" }],
  sparePartName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  sparePartCode: [{ required: true, message: "编码不能为空", trigger: "blur" }],
  typeCode: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  brandCode: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
  supplyModel: [{ required: true, message: "厂商型号不能为空", trigger: "blur" }],
  alarmStock: [{ required: true, message: "安全库存量不能为空", trigger: "blur" }]
}));
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    initCategory();
    initTypeList();
    initBrandList();
    initSupplyModelList();
    getModuleNameNewValue();
    querySparePartLevelSelect();
    querySparePartUnitSelect();
    queryWarehousePositionSelect();
    queryUsedLifeUnitSelect();
    principalIdList.value = await getEmployeeIdAndName();
    if (props.drawerType === "add") {
      formValue.value.category = "";
      formValue.value.sparePartName = "";
      formValue.value.sparePartCode = "";
      formValue.value.className = "";
      formValue.value.systemVal = "";
      formValue.value.typeCode = "";
      formValue.value.brandCode = "";
      formValue.value.modelCode = "";
      formValue.value.supplyModel = "";
      formValue.value.model = "";
      formValue.value.sparePartUnit = "";
      formValue.value.warehousePosition = "";
      formValue.value.sparePartLevel = "";
      formValue.value.mapNum = "";
      formValue.value.principalId = null;
      formValue.value.principalName = "";
      formValue.value.principalPhone = "";
      formValue.value.usedLife = "";
      formValue.value.usedLifeUnit = "hour";
      formValue.value.remark = "";
      formValue.value.alarmStock = "";
      formValue.value.shouldStock = "";
      formValue.value.maxStock = "";
      formValue.value.pictureLists = [];
      formValue.value.fileLists = [];
      delete formValue.value.id;
      photoType.value = "add";
      fileType.value = "add";
    } else if (props.drawerType === "edit") {
      getDetail();
      photoType.value = "edit";
      fileType.value = "edit";
    } else if (props.drawerType === "copy") {
      getDetail();
      photoType.value = "edit";
      fileType.value = "edit";
    }
  } else {
    formValue.value = {
      id: "",
      category: "",
      sparePartName: "",
      sparePartCode: "",
      className: "",
      typeCode: "",
      brandCode: "",
      modelCode: "",
      supplyModel: "",
      model: "",
      sparePartUnit: "",
      warehousePosition: "",
      sparePartLevel: "",
      mapNum: "",
      principalId: null,
      principalName: "",
      principalPhone: "",
      usedLife: "",
      usedLifeUnit: "hour",
      remark: "",
      alarmStock: "",
      shouldStock: "",
      maxStock: "",
      pictureLists: [],
      fileLists: []
    };
  }
});
// 种类下拉框
const initCategory = async () => {
  const params = { typeCode: "typeCategory" };
  const data = await queryDictData(params);
  categoryList.value = data || [];
};
// 改变种类，清空类型、品牌、厂商型号、厂内型号
const handleCategoryChange = () => {
  typeList.value = [];
  brandList.value = [];
  supplyModelList.value = [];
  formValue.value.typeCode = "";
  formValue.value.brandCode = "";
  formValue.value.modelCode = "";
  formValue.value.supplyModel = "";
  formValue.value.model = "";
};
// 类型下拉框
const initTypeList = async () => {
  const data = await queryListTree_1({ category: formValue.value.category, className: formValue.value.className });
  typeList.value = data || [];
};
// 改变类型，清空类型、品牌、厂商型号、厂内型号
const handleTypeChange = val => {
  brandList.value = [];
  supplyModelList.value = [];
  formValue.value.brandCode = "";
  formValue.value.modelCode = "";
  formValue.value.supplyModel = "";
  formValue.value.model = "";
};
// 品牌下拉框
const initBrandList = async () => {
  const data = await queryBrandList({ typeCode: formValue.value.typeCode });
  brandList.value = data || [];
};
// 改变品牌，清空厂商型号、厂内型号
const handleBrandChange = async () => {
  supplyModelList.value = [];
  formValue.value.modelCode = "";
  formValue.value.supplyModel = "";
  formValue.value.model = "";
};
// 厂商型号下拉框
const initSupplyModelList = async () => {
  const params = { category: formValue.value.category, typeCode: formValue.value.typeCode, brandCode: formValue.value.brandCode };
  const data = await queryListPage_5(params);
  supplyModelList.value = data?.data || [];
};
// 改变厂商型号, 赋值厂内型号、型号
const changeSupplyModel = async () => {
  const arr = supplyModelList.value.filter(item => {
    return item.supplyModel === formValue.value.supplyModel;
  });
  if (arr && arr.length > 0) {
    formValue.value.modelCode = arr[0].code;
    formValue.value.model = arr[0].model;
  } else {
    formValue.value.modelCode = "";
    formValue.value.model = "";
  }
};
// 备件等级下拉框
const querySparePartLevelSelect = async () => {
  sparePartLevelList.value = [];
  const params = {
    typeCode: "sparePartLevel"
  };
  const data = await queryDictData(params);
  sparePartLevelList.value = data;
};
// 单位下拉框
const querySparePartUnitSelect = async () => {
  sparePartUnitList.value = [];
  const params = {
    typeCode: "unit"
  };
  const data = await queryDictData(params);
  sparePartUnitList.value = data;
};
// 库位下拉框
const queryWarehousePositionSelect = async () => {
  warehousePositionList.value = [];
  const params = {
    typeCode: "warehouse"
  };
  const data = await queryDictData(params);
  warehousePositionList.value = data;
};
// 额定使用寿命下拉框
const queryUsedLifeUnitSelect = async () => {
  usedLifeUnitList.value = [];
  const params = {
    typeCode: "sparePartLifeUnit"
  };
  const data = await queryDictData(params);
  usedLifeUnitList.value = data;
};
// 获取principalName
const principalChange = val => {
  const arr = principalIdList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.principalName = arr[0].label;
    formValue.value.principalPhone = arr[0].phone;
  }
};
// 获取getModuleNameNew
const getModuleNameNewValue = async () => {
  const data = await getModuleNameNew({});
  moduleName.value = data;
};
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.sparePartsId
  };
  const data = await getSparePartsLedgerNew(params);
  formValue.value.id = data.id;
  formValue.value.category = data.category;
  formValue.value.sparePartName = data.sparePartName;
  formValue.value.sparePartCode = data.sparePartCode;
  formValue.value.className = data.className;
  formValue.value.systemVal = data.systemVal;
  formValue.value.typeCode = data.typeCode;
  formValue.value.brandCode = data.brandCode;
  formValue.value.modelCode = data.modelCode;
  formValue.value.supplyModel = data.supplyModel;
  formValue.value.model = data.model;
  formValue.value.sparePartUnit = data.sparePartUnit;
  formValue.value.warehousePosition = data.warehousePosition;
  formValue.value.sparePartLevel = data.sparePartLevel;
  formValue.value.mapNum = data.mapNum;
  formValue.value.principalId = data.principalId;
  formValue.value.principalName = data.principalName;
  formValue.value.principalPhone = data.principalPhone;
  formValue.value.usedLife = data.usedLife;
  formValue.value.usedLifeUnit = data.usedLifeUnit;
  formValue.value.remark = data.remark;
  formValue.value.alarmStock = data.alarmStock;
  formValue.value.shouldStock = data.shouldStock;
  formValue.value.maxStock = data.maxStock;
  if (data.pictureList && data.pictureList.length > 0) {
    data.pictureList.forEach(item => {
      item.url = item.fileUrl;
    });
    formValue.value.pictureLists = data.pictureList;
  } else {
    formValue.value.pictureLists = [];
  }
  if (data.fileList && data.fileList.length > 0) {
    data.fileList.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    formValue.value.fileLists = data.fileList;
  } else {
    formValue.value.fileLists = [];
  }
  if (props.drawerType === "copy") {
    delete formValue.value.id;
    formValue.value.sparePartCode = "";
  }
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.pictureLists = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 新的文件列表
const changeFileList = val => {
  formValue.value.fileLists = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = formValue.value;
      formValue.value.pictureList = [];
      if (formValue.value.pictureLists && formValue.value.pictureLists.length > 0) {
        formValue.value.pictureLists.forEach(item => {
          if (item?.id) {
            formValue.value.pictureList.push(item.id);
          } else if (item?.response.data.id) {
            formValue.value.pictureList.push(item.response.data.id);
          }
        });
      }
      formValue.value.fileList = [];
      if (formValue.value.fileLists && formValue.value.fileLists.length > 0) {
        formValue.value.fileLists.forEach(item => {
          if (item?.id) {
            formValue.value.fileList.push(item.id);
          } else if (item?.response.data.id) {
            formValue.value.fileList.push(item.response.data.id);
          }
        });
      }
      params.shouldStock = formValue.value.shouldStock == null ? 0 : formValue.value.shouldStock;
      params.maxStock = formValue.value.maxStock == null ? 99999 : formValue.value.maxStock;
      if (props.drawerType === "add" || props.drawerType === "copy") {
        await addSparePartsLedgerNew(params);
        PxMessage.success("创建成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await editSparePartsLedgerNew(params);
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  formRef.value?.resetFields(["systemVal"]);
  typeList.value = [];
  brandList.value = [];
  supplyModelList.value = [];
  formValue.value.typeCode = "";
  formValue.value.brandCode = "";
  formValue.value.modelCode = "";
  formValue.value.supplyModel = "";
  formValue.value.model = "";
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemVal = val3;
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemVal = val;
};
// 系统组件值改变触发
const clearSystem = val => {
  formRef.value?.resetFields(["systemVal"]);
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
